package cn.chiship.framework.third.biz.wxpub.service.impl;

import cn.chiship.framework.common.service.GlobalCacheService;
import cn.chiship.framework.third.core.common.AssignButton;
import cn.chiship.framework.third.core.common.ThirdUtil;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.third.biz.wxpub.mapper.ThirdWechatMenuMapper;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatMenu;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatMenuExample;
import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatMenuService;
import cn.chiship.sdk.third.core.wx.pub.entity.WxPubButton;
import cn.chiship.sdk.third.core.wx.pub.entity.WxPubMenu;
import cn.chiship.sdk.third.service.WxPubService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 微信菜单业务接口实现层 2022/6/19
 *
 * @author lijian
 */
@Service
public class ThirdWechatMenuServiceImpl extends BaseServiceImpl<ThirdWechatMenu, ThirdWechatMenuExample>
        implements ThirdWechatMenuService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdWechatMenuServiceImpl.class);

    @Resource
    ThirdWechatMenuMapper thirdWechatMenuMapper;

    @Resource
    private GlobalCacheService globalCacheService;

    @Resource
    private WxPubService wxPubService;

    void wxPubServiceConfig() {
        wxPubService.config(globalCacheService.getWeiXinConfigByAppId(ThirdUtil.getAppId())).token();
    }

    @Override
    public List<JSONObject> treeTable(String appId) {
        List<JSONObject> menus = new ArrayList<>();
        ThirdWechatMenuExample wechatMenuExample = new ThirdWechatMenuExample();
        wechatMenuExample.createCriteria().andPidEqualTo("0").andIsDeletedEqualTo(BaseConstants.NO)
                .andAppIdEqualTo(appId);
        wechatMenuExample.setOrderByClause(" orders desc ");
        List<ThirdWechatMenu> weChatMenus = thirdWechatMenuMapper.selectByExample(wechatMenuExample);
        for (ThirdWechatMenu wechatMenu : weChatMenus) {
            JSONObject json = JSON.parseObject(JSON.toJSONString(wechatMenu));
            wechatMenuExample = new ThirdWechatMenuExample();
            wechatMenuExample.createCriteria().andPidEqualTo(wechatMenu.getId()).andIsDeletedEqualTo(BaseConstants.NO);
            wechatMenuExample.setOrderByClause(" orders desc ");
            List<ThirdWechatMenu> childWeChatMenus = thirdWechatMenuMapper.selectByExample(wechatMenuExample);
            json.put("children", JSON.parseArray(JSON.toJSONString(childWeChatMenus)));
            menus.add(json);
        }
        return menus;
    }

    private static final String ROOT_ID = "0";

    private static final int MAX_FIRST_MENU = 3;

    private static final int MAX_SECOND_MENU = 5;

    @Override
    public BaseResult insertSelective(ThirdWechatMenu wechatMenu) {
        if (ROOT_ID.equals(wechatMenu.getPid())) {
            ThirdWechatMenuExample wechatMenuExample = new ThirdWechatMenuExample();
            wechatMenuExample.createCriteria().andPidEqualTo(ROOT_ID).andAppIdEqualTo(wechatMenu.getAppId());
            if (thirdWechatMenuMapper.countByExample(wechatMenuExample) >= MAX_FIRST_MENU) {
                return new BaseResult(Boolean.FALSE, BaseResultEnum.FAILED, "最多只能创建3个一级菜单");
            }
        } else {
            ThirdWechatMenuExample wechatMenuExample = new ThirdWechatMenuExample();
            wechatMenuExample.createCriteria().andPidEqualTo(wechatMenu.getPid())
                    .andAppIdEqualTo(wechatMenu.getAppId());
            if (thirdWechatMenuMapper.countByExample(wechatMenuExample) >= MAX_SECOND_MENU) {
                return new BaseResult(Boolean.FALSE, BaseResultEnum.FAILED, "最多只能创建5个二个级菜单");
            }
        }
        ThirdWechatMenuExample wechatMenuExample = new ThirdWechatMenuExample();
        wechatMenuExample.createCriteria().andNameEqualTo(wechatMenu.getName()).andAppIdEqualTo(wechatMenu.getAppId())
                .andPidEqualTo(wechatMenu.getPid());
        List<ThirdWechatMenu> weChatMenus = thirdWechatMenuMapper.selectByExample(wechatMenuExample);
        if (weChatMenus.isEmpty()) {
            return super.insertSelective(wechatMenu);
        } else {
            return new BaseResult(Boolean.FALSE, BaseResultEnum.FAILED, "菜单名称已存在,请重新输入");
        }

    }

    @Override
    public BaseResult updateByPrimaryKeySelective(ThirdWechatMenu wechatMenu) {
        ThirdWechatMenuExample wechatMenuExample = new ThirdWechatMenuExample();
        wechatMenuExample.createCriteria().andNameEqualTo(wechatMenu.getName()).andAppIdEqualTo(wechatMenu.getAppId())
                .andPidEqualTo(wechatMenu.getPid()).andIdNotEqualTo(wechatMenu.getId());
        List<ThirdWechatMenu> weChatMenus = thirdWechatMenuMapper.selectByExample(wechatMenuExample);
        if (weChatMenus.isEmpty()) {
            return super.updateByPrimaryKeySelective(wechatMenu);
        } else {
            return new BaseResult(Boolean.FALSE, BaseResultEnum.FAILED, "菜单名称已存在,请重新输入");
        }
    }

    @Override
    public BaseResult releaseMenu(String appId) {
        WxPubMenu wxPubMenu = new WxPubMenu();

        List<WxPubButton> firstButtons = new ArrayList<>();
        ThirdWechatMenuExample wechatMenuExample = new ThirdWechatMenuExample();
        wechatMenuExample.createCriteria().andPidEqualTo("0").andIsDeletedEqualTo(BaseConstants.NO)
                .andAppIdEqualTo(appId);
        wechatMenuExample.setOrderByClause(" orders desc ");
        List<ThirdWechatMenu> weChatMenus = thirdWechatMenuMapper.selectByExample(wechatMenuExample);
        for (ThirdWechatMenu wechatMenu : weChatMenus) {
            List<WxPubButton> secondButtons = null;
            wechatMenuExample = new ThirdWechatMenuExample();
            wechatMenuExample.createCriteria().andPidEqualTo(wechatMenu.getId()).andIsDeletedEqualTo(BaseConstants.NO);
            wechatMenuExample.setOrderByClause(" orders desc ");
            List<ThirdWechatMenu> childWeChatMenus = thirdWechatMenuMapper.selectByExample(wechatMenuExample);
            if (!childWeChatMenus.isEmpty()) {
                secondButtons = new ArrayList<>();
                for (ThirdWechatMenu second : childWeChatMenus) {
                    secondButtons.add(AssignButton.menuToButton(second));
                }
            }
            WxPubButton button = AssignButton.menuToButton(wechatMenu);
            button.setWxPubButtons(secondButtons);
            firstButtons.add(button);
        }
        wxPubMenu.setWxPubButton(firstButtons);
        wxPubServiceConfig();
        return wxPubService.createMenu(wxPubMenu);
    }

}
